import React, { useEffect, useState } from 'react'
import { Button, Select, Space, Divider, Radio, Table, ConfigProvider, message } from 'antd'
import { SettingOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import ChargeSearch from '../../components/Charge/ChargeSearch'
import type { TableRowSelection } from 'antd/es/table/interface';
import { getAllCharge } from '../../apis/charge';
import zh_CN from 'antd/es/locale/zh_CN'
import { upDateAllCharge } from '../../apis/charge';
import ExportJsonExcel from 'js-export-excel'

type Props = {}

interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}





const Charge = (props: Props) => {
  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    getAllChargeData()
  }, [])

  const columns: ColumnsType<DataType> = [
    {
      title: '充电站名称',
      dataIndex: 'shopName',
    },
    {
      title: '电话',
      dataIndex: 'tel',
    },
    {
      title: '地址',
      dataIndex: 'address',
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
    },
    {
      title: '负责人',
      dataIndex: 'managerName',
    },
    {
      title: '执照号',
      dataIndex: 'licenceNo',
    },
    {
      title: '状态',
      dataIndex: 'status',
    },
    {
      title: '执照图片',
      dataIndex: 'licenceImg',
      render: (text, val: any) => (
        <img src={val.licenceImg} alt="" style={{ width: '30px' }} />
      )
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, val) => (
        <Button onClick={() => upDateBtn(val)}>修改状态</Button>
      )
    },
  ];

  //修改状态
  const upDateBtn = async (val: any) => {
    console.log(val.status);
    if (val.status === '通过') {
      const res = await upDateAllCharge({
        ...val,
        status: '拒绝'
      })
      // console.log(res);
      if (res.status === 200) {
        message.success('修改成功！')
      } else {
        message.error("修改失败！")
      }

    } else {
      const res = await upDateAllCharge({
        ...val,
        status: '通过'
      })
      // console.log(res);
      if (res.status === 200) {
        message.success('修改成功！')
      } else {
        message.error("修改失败！")
      }
    }
    getAllChargeData()
  }

  const getAllChargeData = async (val?: any) => {
    const res = await getAllCharge(val)
    console.log(res);
    if (res.status === 200) {
      setData(res.data.rows)
      setTotal(res.data.total)
    }
  }


  //导出excel
  // const handleChange = (value: string) => {
  //   console.log(`selected ${value}`);
  // };

  //导出表格的方法，只看方法
  const downloadFileToExcel = () => {
    const datas = data.length != 0 ? data : '';//表格数据
    console.log('datas', datas);

    var option: any = {};
    let dataTable: any = [];
    if (datas) {
      datas.map((item: any) => {
        let obj = {
          shopName: item.shopName,
          tel: item.tel,
          address: item.address,
          idCard: item.idCard,
          managerName: item.managerName,
          licenceNo: item.licenceNo,
          status: item.status,
          licenceImg: item.licenceImg,
        }
        dataTable.push(obj);
        return dataTable
      })

    }
    option.shopName = '充电站名称'
    option.fileName = 'Charge列表'
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: 'Charge',
        sheetFilter: ['tel', 'address', 'idCard', 'managerName', 'licenceNo', 'status', 'licenceImg'],
        sheetHeader: ['电话', '地址', '身份证号', '负责人', '执照号', '状态', '执行图片'],
      }
    ];
    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  }

  //搜索
  const getSeaData = (val: any) => {
    // console.log('getSeaData',val);
    getAllChargeData(val)
  }

  //获取页数和当前页
  const updatePage = (val: any) => {
    console.log('val', val);
    const data = {
      pageNum: val.current,
      pageSize: val.pageSize
    }
    getAllChargeData(data)
  }

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  //重置
  const resetting = () =>{
    getAllChargeData()
  }

  return (
    <div>
      {/* 搜索 */}
      <div style={{ marginTop: '30px' }}>
        <ChargeSearch getSeaData={getSeaData} resetting={resetting}></ChargeSearch>
      </div>
      {/* 操作 */}
      <div style={{ width: '280px', display: 'flex', justifyContent: 'space-between', marginLeft: '20px' }}>
        <Button style={{ color: 'rgb(64,169,255)', border: '1px solid rgb(64,169,255)' }}>新增</Button>
        <Button>删除</Button>
        {/* <Select
          defaultValue="更多操作"
          style={{ width: 120 }}
          onChange={handleChange}
          options={[
            { value: 'Excel', label: 'Excel' },
          ]}
        /> */}
        <Button onClick={downloadFileToExcel}>导出Excel</Button>
      </div>
      {/* table */}
      <div style={{ marginTop: '20px' }}>
        <ConfigProvider locale={zh_CN}>
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={data}
            rowKey='id'
            pagination={{ total: total, pageSizeOptions: [10, 20, 50, 100], showQuickJumper: true, showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条记录, 共 ${total} 条数据` }} onChange={updatePage}
          />
        </ConfigProvider>
      </div>
    </div>
  )
}

export default Charge